package main

import (
	"context"
	"fmt"
	grpc2 "go-guide/rpc/grpc"
	"google.golang.org/grpc"
	"io"
	"net"
)

type HelloService struct {
}

func (hs HelloService) SayHello(ctx context.Context, request *grpc2.HelloRequest) (*grpc2.HelloResponse, error) {
	return &grpc2.HelloResponse{
		Message: fmt.Sprintf("Hello, %s", request.GetUsername()),
	}, nil
}

func (hs HelloService) Chat(conn grpc2.HelloService_ChatServer) error {
	for {
		stream, err := conn.Recv()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
		fmt.Println("receive from client:", stream.Stream)

		conn.Send(&grpc2.ServerStream{
			Stream: newBytes(1, 2, 3, 4, 5),
		})
	}
	return nil
}

func main() {
	listener, err := net.Listen("tcp", ":6001")
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	server := grpc.NewServer()
	grpc2.RegisterHelloServiceServer(server, HelloService{})
	go func() {
		server.Serve(listener)
	}()
	fmt.Println(server.GetServiceInfo())
	select {}
}

func newBytes(a ...byte) []byte {
	return a
}
